<template>
  <div class="candidate-screening-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>我的简历初筛结果</h2>
          <el-badge :value="unreadCount" class="notification-badge" />
        </div>
      </template>

      <!-- 简历列表 -->
      <el-table
        :data="deliveryList"
        border
        style="width: 100%"
        @row-click="handleRowClick"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="jobName" label="职位名称" width="200" />
        <el-table-column prop="companyName" label="公司" width="150" />
        <el-table-column prop="deliveryTime" label="投递时间" width="160" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === '通过' ? 'success' : 'info'"
            >
              {{ scope.row.status || '待筛选' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 初筛报告详情弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        title="AI初筛报告"
        width="60%"
      >
        <div v-if="loadingReport" class="loading-container">
          <el-spin tip="加载中..." />
        </div>
        <div v-else-if="currentReport">
          <el-descriptions column="1" border>
            <el-descriptions-item label="综合匹配分">
              <span class="score">{{ currentReport.ai_match_score }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="你的优势">
              <div class="points match-points">
                <div v-for="(point, idx) in currentReport.match_points" :key="idx">
                  <i class="el-icon-check-circle" /> {{ point }}
                </div>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="待提升点">
              <div class="points risk-points">
                <div v-for="(point, idx) in currentReport.risk_points" :key="idx">
                  <i class="el-icon-warning" /> {{ point }}
                </div>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="求职建议">
              <div class="suggestion">{{ currentReport.user_evaluation }}</div>
            </el-descriptions-item>
            <el-descriptions-item label="初筛结果">
              <el-tag :type="currentReport.passed ? 'success' : 'danger'" size="large">
                {{ currentReport.passed ? '通过' : '未通过' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div v-else>
          <el-empty description="暂无初筛结果" />
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import {
  ElMessage,
  ElNotification,
  ElTag,
  ElDescriptions,
  ElDescriptionsItem,
  // ElSpin,  // 正确导入
  ElEmpty,
  ElBadge,
  ElDialog,  // 若使用了弹窗需导入
  // ElIcon     // 若使用了图标需导入
} from 'element-plus'

// 状态管理
const userId = localStorage.getItem('user.id') || 2 // 从本地存储获取当前用户ID，默认值为2（测试用）
const deliveryList = ref([]) // 投递列表
const currentReport = ref(null) // 当前选中的初筛报告
const dialogVisible = ref(false) // 报告弹窗显示状态
const loadingReport = ref(false) // 报告加载状态
const unreadCount = ref(0) // 未读通知计数
let ws = null // WebSocket实例

// 获取用户所有投递记录
const fetchDeliveryList = async () => {
  try {
    const res = await axios.get('http://127.0.0.1:8000/job/myDeliveries/', {
      params: { user_id: userId }
    })
    if (res.data.code === 200) {
      deliveryList.value = res.data.data.map(item => ({
        id: item.id,
        jobId: item.jobposting_id,
        resumeId: item.jobinfo_id,
        jobName: item.jobposting.title,
        companyName: item.jobposting.company.name,
        deliveryTime: item.created_at,
        status: item.inter_status === 1 ? '通过' : '待筛选',
        inter_status: item.inter_status // 新增：保存原始状态值用于判断
      }))
    }
  } catch (error) {
    ElMessage.error('获取投递记录失败')
    console.error(error)
  }
}

// 获取指定投递的初筛报告（仅当通过时调用）
const fetchReport = async (jobId, resumeId) => {
  loadingReport.value = true
  try {
    const res = await axios.get('http://127.0.0.1:8000/job/aiReport/', {
      params: {
        user_id: userId,
        job_id: jobId,
        resume_id: resumeId
      }
    })
    if (res.data.code === 200) {
      currentReport.value = res.data.data
    } else {
      ElMessage.warning('未查询到初筛结果')
      currentReport.value = null
    }
  } catch (error) {
    ElMessage.error('获取初筛报告失败')
    currentReport.value = null
  } finally {
    loadingReport.value = false
  }
}

// 表格行点击事件：根据状态判断是否显示弹窗
const handleRowClick = (row) => {
  // 核心修改：仅当inter_status=1（通过）时显示弹窗
  if (row.inter_status === 1) {
    fetchReport(row.jobId, row.resumeId)
    dialogVisible.value = true
  } else {
    // 未通过或待筛选状态提示
    ElMessage({
      message: '该简历未通过初筛或尚未处理',
      type: 'info',
      duration: 2000
    })
  }
}

// 表格行样式：新推送的结果高亮
const tableRowClassName = ({ row }) => {
  return row.isNew ? 'highlight-row' : ''
}

// 初始化WebSocket连接
const initWebSocket = () => {
  if (!userId) {
    ElMessage.warning('请先登录')
    return
  }

  // 关闭已有连接
  if (ws) ws.close()

  // 连接求职者专属WebSocket
  ws = new WebSocket(`ws://127.0.0.1:8000/ws/screening/user/${userId}/`)

  // 连接成功
  ws.onopen = () => {
    console.log('求职者WebSocket连接成功')
  }

  // 接收消息（初筛结果推送）
  ws.onmessage = (event) => {
    const data = JSON.parse(event.data)
    if (data.type === 'screening_result') {
      handleScreeningResult(data)
    }
  }

  // 连接错误
  ws.onerror = () => {
    ElMessage.error('WebSocket连接异常')
  }

  // 连接关闭
  ws.onclose = () => {
    console.log('WebSocket连接关闭，尝试重连...')
    setTimeout(initWebSocket, 3000) // 3秒后重连
  }
}

// 处理推送的初筛结果（仅处理通过的）
const handleScreeningResult = (data) => {
  const { evaluation, deliverjob_id } = data
  const score = evaluation?.score_info?.score || 0

  // 仅当通过初筛（score >= 0.5）时处理
  if (score >= 0.5) {
    // 1. 显示通知
    ElNotification.success({
      title: '新的初筛结果',
      message: `你投递的职位已通过初筛，点击查看详情`,
      duration: 5000
    })

    // 2. 更新未读计数
    unreadCount.value += 1

    // 3. 刷新投递列表，标记新结果
    fetchDeliveryList().then(() => {
      const targetRow = deliveryList.value.find(row => row.id === deliverjob_id)
      if (targetRow) {
        targetRow.status = '通过'
        targetRow.inter_status = 1 // 标记为通过状态
        targetRow.isNew = true // 高亮新结果
      }
    })
  }
}

// 页面挂载时初始化
onMounted(() => {
  fetchDeliveryList()
  initWebSocket()
})

// 页面卸载时关闭连接
onUnmounted(() => {
  if (ws) ws.close()
})
</script>

<style scoped>
/* 原有样式保持不变 */
.candidate-screening-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.notification-badge {
  background-color: #f56c6c;
}
.loading-container {
  text-align: center;
  padding: 50px 0;
}
.report-content {
  padding: 10px 0;
}
.score {
  font-size: 24px;
  color: #1890ff;
  font-weight: bold;
}
.points {
  line-height: 1.8;
}
.match-points {
  color: #52c41a;
}
.risk-points {
  color: #faad14;
}
.suggestion {
  line-height: 1.8;
  white-space: pre-line;
}
.highlight-row {
  background-color: #e6f7ff !important;
}
</style>